package com.wz.leetcode.array;

import java.util.PriorityQueue;
import java.util.Random;

public class KthLargest_215 {
    private static final Random random = new Random(System.currentTimeMillis());

    public static int findKthLargest(int[] nums, int k) {
        // 最大数是n-1,第k大的树是n-k
        int n = nums.length;
        return quickSelect(nums, 0, n-1, n-k);
    }

    private static int quickSelect(int[] nums, int l, int r, int target) {
        int q = RandomPartition(nums, l, r);
        if (q == target) {
            return nums[q];
        } else {
            return q < target ?
                    quickSelect(nums, q + 1, r, target) :
                    quickSelect(nums, l, q-1, target);
        }
    }

    private static int RandomPartition(int[] nums, int l, int r) {
        int i = random.nextInt(r-l+1) + l;
        swap(nums, i, r);
        return partition(nums, l, r);
    }

    private static int partition(int[] nums, int l, int r) {
        // 双指针，[0, i]都是 <= x， (i, j) > x
        int x = nums[r], i = l - 1;
        for (int j = l; j < r; ++j) {
            if (nums[j] <= x) {
                swap(nums, ++i, j);
            }
        }
        swap(nums, i + 1, r);
        return i+1;
    }

    private static void swap(int[] nums, int left, int index) {
        int tmp = nums[left];
        nums[left] = nums[index];
        nums[index] = tmp;
    }

    public static int findKthLargest1(int[] nums, int k) {
        int n = nums.length;
        // 创建最大堆的方式如下
//        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k, Collections.reverseOrder());
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
        for (int i = 0; i < k; i++) {
            minHeap.offer(nums[i]);
        }
        for (int i = k; i < n; i++) {
            Integer top = minHeap.peek();
            if (nums[i] > top) {
                minHeap.poll();
                minHeap.offer(nums[i]);
            }
        }
        return minHeap.peek();
    }

    public static void main(String[] args) {
        System.out.println(findKthLargest(new int[]{3, 2, 1, 5, 6, 4}, 2));
        System.out.println(findKthLargest(new int[]{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4));
        System.out.println(findKthLargest1(new int[]{3, 2, 1, 5, 6, 4}, 2));
        System.out.println(findKthLargest1(new int[]{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4));
    }
}
